package com.steve.combat.thread.多线程交替打印ABC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: STEVE
 * @Description: 使用ReentrantLock和Condition
 * @since: 2025-06-01
 */
public class PrintABCUsingReentrantLock {

    /**
     * 实现步骤
     * 定义一个ReentrantLock和多个Condition。
     * 每个线程等待相应的Condition，当符合条件时打印字符并唤醒下一个线程。
     */

    private final Lock lock = new ReentrantLock();
    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();
    private final Condition conditionC = lock.newCondition();
    private int state = 0;  // 0:A 1:B 2:C

    public static void main(String[] args) {
        PrintABCUsingReentrantLock task = new PrintABCUsingReentrantLock();

        Thread threadA = new Thread(task::printA);
        Thread threadB = new Thread(task::printB);
        Thread threadC = new Thread(task::printC);

        threadA.start();
        threadB.start();
        threadC.start();
    }

    public void printA() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                while (state != 0) {
                    conditionA.await();
                }
                System.out.print("A");
                state = 1;
                conditionB.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                while (state != 1) {
                    conditionB.await();
                }
                System.out.print("B");
                state = 2;
                conditionC.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                while (state != 2) {
                    conditionC.await();
                }
                System.out.print("C");
                state = 0;
                conditionA.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
